from django.shortcuts import render, HttpResponse
from django.http import JsonResponse
from django.views import View
from libs.captcha.captcha import captcha
from libs.rl_sms import send_message
# Create your views here.
from redis import StrictRedis
import random


# 生成图形验证码
class ImageCodeView(View):
    '''图形验证码'''

    def get(self, request, uuid):
        """
        :param request: 请求对象
        :param uuid: 唯一标识图形验证码所属于的用户
        :return: image/jpg
        """
        # 生成图片及答案
        text, image = captcha.generate_captcha()
        # 保存答案和uuid到redis中
        client = StrictRedis()  # 127.0.0.1:6379
        client.set(uuid, text)
        return HttpResponse(image, content_type='image/jpeg')
        pass


# 发送短信验证码
class SMSCodeView(View):
    '''短信验证码'''

    def get(self, request, mobile):
        # 接受参数
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('uuid')
        # 校验参数
        if not all([mobile, image_code, uuid]):
            return JsonResponse({'code': 999, 'msg': '缺少必要参数'})
        # 判断图形验证码
        # 1.从redis中取
        client = StrictRedis()
        redis_image_code = client.get(uuid)
        # 2.从redis中删除
        client.delete(uuid)
        # 3.对比
        if redis_image_code:
            redis_image_code = redis_image_code.decode()
        else:
            redis_image_code = None
        if image_code.upper() == redis_image_code:
            pass
        else:
            return JsonResponse({'code': 999, 'msg': '图形验证码不正确'})
        # 生成短信验证码
        sms_code = "%04d" % random.randint(0, 9999)
        # 把短信存到redis中
        client.setex(mobile, 5 * 60, sms_code)
        # 发送短信验证码
        import os
        import sys
        from meiduo.settings import BASE_DIR
        sys.path.insert(0,os.path.join(BASE_DIR,'../celery_task/'))
        from main import send_sms_code
        send_sms_code.delay(mobile, sms_code, 5)
        return JsonResponse({'code': '0', 'msg': 'ok'})
